package com.xiaoyun.execption;

import com.xiaoyun.utils.IMoocJSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.Valid;
import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截表单参数校验
     */
//    @ResponseStatus(HttpStatus.OK)
//    @Valid
    @ExceptionHandler({BindException.class})
    public IMoocJSONResult bindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        return IMoocJSONResult.errorMap(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }

//    @Validated
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public IMoocJSONResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        return IMoocJSONResult.errorMap(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }


    @ExceptionHandler(Exception.class)
    public IMoocJSONResult exceptionHandler(Exception e) {
        e.printStackTrace();
        return null;
    }
}
